import hashlib
import time

from flask import render_template, request, jsonify, session, redirect, url_for

from models import db
from models.index import User, Post, Comment
from utils.image_qiniu import upload_image_to_qiniu
from views import user_blu


# 设置
@user_blu.route('/user/set', methods=['POST', 'GET'])
def set():
    method = request.method
    if method == 'GET':
        user_id = session.get('user_id')
        nick_name = session.get('nick_name')
        user = db.session.query(User).filter(User.id == user_id).first()
        return render_template('./user/set.html', user=user, nick_name=nick_name)
    else:
        email = request.form.get('email')
        nick_name = request.form.get('nick_name')
        gender = request.form.get('gender')
        city = request.form.get('city')
        signature = request.form.get('sign')

        user_id = session.get('user_id')

        user = db.session.query(User).filter(User.id == user_id).first()
        if not user:
            ret = {
                "errno": 4002,
                "errmsg": "没有此用户"
            }

            return jsonify(ret)

        # 如果查询到此用户就修改数据

        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        user.email = email
        user.city = city

        db.session.commit()

        ret = {
            'errno': 0,
            'errmsg': '修改成功'
        }
        return jsonify(ret)


# 重置密码
@user_blu.route('/user/repass', methods=['POST'])
def repass():
    old_password = request.form.get("nowpass")
    new_password = request.form.get("pass")
    re_new_password = request.form.get("repass")

    # 2. 提取当前用户的id
    user_id = session.get("user_id")
    if not user_id:
        return jsonify({
            "errno": 4001,
            "errmsg": "请先登录"
        })

    # 2. 判断旧密码与数据中的当前存储的密码是否相同
    user = db.session.query(User).filter(User.id == user_id, User.password_hash == old_password).first()

    # 3. 如果相同，则修改
    if user:
        user.password_hash = new_password
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "修改成功"
        }

    else:
        ret = {
            "errno": 4004,
            "errmsg": "原密码错误！"
        }

    # 4. 返回json
    return jsonify(ret)


# 消息
# @user_blu.route('/user/message')
# def message():
#     page = int(request.args.get("page", 1))
#     user_id = session.get("user_id")
#     user = db.session.query(User).filter(User.id == user_id).first()
#     if not user_id:
#         return redirect(url_for('index_blu.index'))
#     # 获取当前用户的所有新闻
#     # post_paginate_comments = user.comments.order_by(-Comment.create_time).paginate(page, 4, False)
#     post_paginate_comments = user.comments.filter(Comment.post_id == Post.id).order_by(-Comment.create_time).paginate(page, 4, False)
#     # post_paginate_comments = user.post.filter(Post.id == Comment.post_id).order_by(-Comment.create_time).paginate(page, 4, False)
#     post_paginate_post = user.post.order_by(-Post.create_time).paginate(page, 4, False)
#     return render_template('./user/message.html', user=user, post_paginate_post=post_paginate_post,
#                            post_paginate_comments=post_paginate_comments)


# 个人中心
@user_blu.route('/user/home')
def home():
    page = int(request.args.get("page", 1))
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    if not user_id:
        return redirect(url_for('index_blu.index'))
    # 获取当前用户的所有新闻
    post_paginate = user.post.paginate(page, 1, False)
    post_paginate_comments = user.comments.order_by(-Comment.create_time).paginate(page, 4, False)

    time_Rank = db.session.query(Post).filter(Post.user_id == user_id).order_by(-Post.create_time).limit(6)
    return render_template('./user/home.html', post_paginate=post_paginate, user=user, time_Rank=time_Rank,
                           post_paginate_comments=post_paginate_comments)


@user_blu.route('/user/home/<int:id>')
def home_id(id):
    page = int(request.args.get("page", 1))
    user = db.session.query(User).filter(User.id == id).first()
    post_id = session.get('post_id')
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('index_blu.index'))
    # 获取当前用户的所有新闻
    post_paginate = user.post.paginate(page, 1, False)
    post_paginate_comments = user.comments.order_by(-Comment.create_time).paginate(page, 4, False)

    time_Rank = db.session.query(Post).filter(Post.user_id == id).order_by(-Post.create_time).limit(6)
    return render_template('./user/home.html', post_paginate=post_paginate, user=user, time_Rank=time_Rank,
                           post_paginate_comments=post_paginate_comments)




@user_blu.route('/user/index')
def index():
    page = int(request.args.get("page", 1))
    user_id = session.get("user_id")
    print('-----------------', user_id)
    if not user_id:
        return render_template('./user/login.html')
    user = db.session.query(User).filter(User.id == user_id).first()
    # 获取当前用户的所有新闻
    post_paginate = user.post.paginate(page, 6, False)
    return render_template('./user/index.html', post_paginate=post_paginate, user=user)


@user_blu.route('/user/activate')
def activate():
    return render_template('./user/activate.html')


@user_blu.route('/user/avatar', methods=['POST'])
def avatar():
    f = request.files.get("avatar")
    print(f)
    if f:
        # 为了防止多个用户上传的图片名字相同，需要将用户的图片计算出一个随机的用户名，防止冲突
        file_hash = hashlib.md5()
        file_hash.update((f.filename + time.ctime()).encode("utf-8"))
        file_name = file_hash.hexdigest() + f.filename[f.filename.rfind("."):]
        # 用新的随机的名字当做图片的名字
        path_file_name = "./static/images" + file_name
        f.save(path_file_name)

        # 将这个图片上传到七牛云
        qiniu_avatar_url = upload_image_to_qiniu(path_file_name, file_name)
        avatar_url = file_name

        user_id = session.get("user_id")
        user = db.session.query(User).filter(User.id == user_id).first()
        user.avatar_url = qiniu_avatar_url
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "成功",
            "avatar_url": user.avatar_url
        }
    else:
        ret = {
            "errno": 4003,
            "errmsg": "上传失败"
        }

    return jsonify(ret)
